package com.aixingfu.sports.ui.activity;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aixingfu.sports.Adapter.PaymentAdapter;
import com.aixingfu.sports.Adapter.PaymentTypeAdapter;
import com.aixingfu.sports.Adapter.PaymetAdapter;
import com.aixingfu.sports.Adapter.RecyclerTouchListener;
import com.aixingfu.sports.MVP.contract.DepositContract;
import com.aixingfu.sports.MVP.contract.OrderSaveContract;
import com.aixingfu.sports.MVP.contract.UserPayContract;
import com.aixingfu.sports.MVP.presenter.DepositPresenter;
import com.aixingfu.sports.MVP.presenter.OrderSavePresenter;
import com.aixingfu.sports.MVP.presenter.UserPayPresenter;
import com.aixingfu.sports.Model.DepositModel;
import com.aixingfu.sports.Model.OrderSaveModel;
import com.aixingfu.sports.Model.UserPayModel;
import com.aixingfu.sports.R;
import com.aixingfu.sports.bean.PaymentBean;
import com.aixingfu.sports.bean.PaymentMBean;
import com.aixingfu.sports.view.PopPayMethodCheckChooseID;
import com.aixingfu.sports.view.PopupWindowCheckChoose;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.orie.librarybase.base.BaseActivity;
import com.orie.librarybase.utils.MoneyEditUtils;
import com.orie.librarybase.utils.UserUtils;
import com.vondear.rxtool.view.RxToast;
import com.vondear.rxui.view.dialog.RxDialogSureCancel;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

//付款
@Route(path = "/main/PaymentActivity")
public class PaymentActivity extends BaseActivity implements UserPayContract.MyView, OrderSaveContract.MyView, DepositContract.MyView, PaymentTypeAdapter.OnItemEditTextChangedListener {

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_add)
    ImageView ivAdd;
    @BindView(R.id.tv_back)
    TextView tvBack;
    @BindView(R.id.tv_next)
    TextView tvNext;
    @BindView(R.id.rl_add_type)
    RelativeLayout rlAddType;
    @BindView(R.id.ed_receipt_number)
    EditText edReceiptNumber;
    @BindView(R.id.tv_collect_way)
    TextView tvCollectWay;
    @BindView(R.id.recycle_type)
    RecyclerView recycleType;
    @BindView(R.id.ll_type)
    LinearLayout llType;
    @BindView(R.id.ll_deposit)
    LinearLayout llDeposit;
    @BindView(R.id.ed_deposit)
    EditText edDeposit;
    @BindView(R.id.tv_deposit)
    TextView tvDeposit;
    private UserPayPresenter userPayPresenter;
    private PaymetAdapter paymetAdapter;
    private List<PaymentBean> paymentBeansList = new ArrayList<>();
    private List<PaymentMBean> paymentMBeansList = new ArrayList<>();
    private ArrayList<String> mList = new ArrayList();
    private List<UserPayModel.DataBean.PayMethodBean> pay_method;
    private PopPayMethodCheckChooseID popPayMethodCheckChooseID;
    private int paymode;
    private int POSITION;
    private OrderSavePresenter orderSavePresenter;
    private PaymentAdapter paymentAdapter;
    private int mposition;
    private PaymentBean paymentBean;
    private String jsonString;
    private double dprice = 0;
    private String order_id = "";
    private String receiptNumber;
    private PopupWindowCheckChoose mPopup;
    private String type = "";
    private String member_id = "";
    private DepositPresenter depositPresenter;
    private RecyclerTouchListener onTouchListener;
    private PaymentTypeAdapter paymentTypeAdapter;
    private String mType = "全款";
    private double mdeposit;


    @Override
    protected int provideContentViewId() {
        return R.layout.activity_payment;
    }

    public static void startActivityByRoute() {
        ARouter.getInstance().build("/main/PaymentActivity").navigation();
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        ButterKnife.bind(this);
        Bundle bundle = getIntent().getExtras();
        type = bundle.getString("type", "");
        member_id = bundle.getString("member_id", "");
        userPayPresenter = new UserPayPresenter();
        userPayPresenter.attachView(this);
        orderSavePresenter = new OrderSavePresenter();
        orderSavePresenter.attachView(this);
//        PaymentBean paymentBean = new PaymentBean();
//        paymentBean.setPayment("请选择支付方式");
//        paymentBean.setPrice("");
//        paymentBeansList.add(paymentBean);
        userPayPresenter.getUserPay();
//        recycleType.setLayoutManager(new LinearLayoutManager(PaymentActivity.this, LinearLayoutManager.VERTICAL, false));
//        paymetAdapter = new PaymetAdapter(PaymentActivity.this, R.layout.item_payment, paymentBeansList);
//        recycleType.addItemDecoration(new SpaceItemDecoration(0, 20));
////        //设置分割线
////        recycleList.addItemDecoration(new DividerItemDecoration(
////                getActivity(), DividerItemDecoration.VERTICAL));
//        recycleType.setAdapter(paymetAdapter);
        paymentTypeAdapter = new PaymentTypeAdapter(this, paymentBeansList);
        paymentTypeAdapter.setListener(this);
        recycleType.setAdapter(paymentTypeAdapter);
        recycleType.setLayoutManager(new LinearLayoutManager(this));
        onTouchListener = new RecyclerTouchListener(this, recycleType);
        onTouchListener.setSwipeable(true);
        onTouchListener.setClickable(true);
        MoneyEditUtils.afterDotTwo(edDeposit);
        onTouchListener
                .setClickable(new RecyclerTouchListener.OnRowClickListener() {
                    @Override
                    public void onRowClicked(int position) {
                    }

                    @Override
                    public void onIndependentViewClicked(int independentViewID, int position) {

                    }
                })
                .setLongClickable(true, new RecyclerTouchListener.OnRowLongClickListener() {
                    @Override
                    public void onRowLongClicked(int position) {
                    }
                })
                .setSwipeOptionViews(R.id.change)
                .setSwipeable(R.id.rowFG, R.id.rowBG, new RecyclerTouchListener.OnSwipeOptionsClickListener() {
                    @Override
                    public void onSwipeOptionClicked(int viewID, int position) {
                        String message = "";
                        if (viewID == R.id.change) {
                            if (position == 0) {
                                return;
                            }
                            paymentBeansList.remove(position);
//                            paymentTypeAdapter.notifyItemRemoved(position);
                            paymentTypeAdapter.setList(paymentBeansList);
//                            paymentTypeAdapter.notifyDataSetChanged();
                        }
                    }
                });
        paymentTypeAdapter.setOnItemClickListener(new PaymentTypeAdapter.OnItemClickListener() {

            @Override
            public void onItemClick(int position, View v) {
                hideIputKeyboard();
                POSITION = position;
                popPayMethodCheckChooseID.showPop(recycleType);
            }
        });


//        paymentAdapter = new PaymentAdapter();
//        paymentAdapter.setListener(this);
//        recycleType.setAdapter(paymentAdapter);
//        recycleType.setLayoutManager(new LinearLayoutManager(this));
//        paymentAdapter.setOnItemClickListener(new PaymentAdapter.OnItemClickListener() {
//            @Override
//            public void onItemClick(int position, View v) {
//                hideIputKeyboard();
//                POSITION = position;
//                popPayMethodCheckChooseID.showPop(recycleType);
//            }
//        });
        setPaymentList();
        mList = getPopList();
        mPopup = new PopupWindowCheckChoose(PaymentActivity.this, mList);
        mPopup.setTagTxt("请选择")//设置顶部title的内容
                .setButtomTxt("取消")//设置底部按钮内容
                .setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);//单选
        //单选
        mPopup.setOnEventLisenter(positionList -> {
            mPopup.dismiss();
            tvCollectWay.setText(mList.get(positionList.get(0)));
            mType = mList.get(positionList.get(0));
            if ("全款".equals(mType)) {
                llDeposit.setVisibility(View.GONE);
            } else if ("使用定金".equals(mType)) {
                llDeposit.setVisibility(View.VISIBLE);
            }
        });
        depositPresenter = new DepositPresenter();
        depositPresenter.attachView(this);
        getDeposit();
//        paymentAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
//            @Override
//            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
//                int id = view.getId();
//                if (id == R.id.ll_payment_method){
//                    POSITION = position;
//                    popPayMethodCheckChooseID.showPop(recycleType);
//                }
//            }
//        });
    }

    /**
     * 数据
     *
     * @return
     */
    public ArrayList<String> getPopList() {
        ArrayList<String> popList = new ArrayList<>();
        popList.add("全款");
        popList.add("使用定金");
        return popList;
    }

    public void setPaymentList() {
        PaymentBean paymentBean = new PaymentBean();
        paymentBean.setPayment("请选择支付方式");
        paymentBean.setPrice("");
        paymentBeansList.add(paymentBean);
        paymentTypeAdapter.setList(paymentBeansList);

    }

    @Override
    protected void initEvent() {

    }

    @Override
    protected void beforeInit() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    private int PAYMODE = 0;
    private PaymentMBean paymentMBean;

    @OnClick({R.id.iv_add, R.id.rl_add_type, R.id.ll_type, R.id.tv_back, R.id.tv_next})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_add:
                break;
            case R.id.ll_type:
                if ("1".equals(type)) {
                    hideIputKeyboard();
                    mPopup.showPop(tvCollectWay);
                }
                break;
            case R.id.rl_add_type:
                hideIputKeyboard();
                PaymentBean mpaymentBean = new PaymentBean();
                mpaymentBean.setPayment("请选择支付方式");
                mpaymentBean.setPrice("");
                paymentBeansList.add(mpaymentBean);
                paymentTypeAdapter.setList(paymentBeansList);
                break;
            case R.id.tv_back:
                hideIputKeyboard();
                finish();
                break;
            case R.id.tv_next:

                hideIputKeyboard();
                dprice = 0;
                PAYMODE = 0;
                String price = "0";
                paymentMBeansList.clear();
                receiptNumber = edReceiptNumber.getText().toString();
                for (int i = 0; i < paymentBeansList.size(); i++) {
                    paymentMBean = new PaymentMBean();
                    paymentMBean.setPrice(paymentBeansList.get(i).getPrice());
                    paymentMBean.setType(paymentBeansList.get(i).getType());
                    paymentMBeansList.add(paymentMBean);
                }
                jsonString = JSON.toJSONString(paymentMBeansList);
                for (int i = 0; i < paymentBeansList.size(); i++) {
                    price = paymentBeansList.get(i).getPrice();
                    String type = paymentBeansList.get(i).getType();
                    if (TextUtils.isEmpty(price)) {
                        PAYMODE = 1;
                        break;
                    } else if (TextUtils.isEmpty(type)) {
                        PAYMODE = 2;
                        break;
                    } else {
                        if (TextUtils.isEmpty(price)) {
                            price = "0";
                        } else {
                            price = paymentBeansList.get(i).getPrice();
                        }
                        double mprice = Double.parseDouble(price);
                        this.dprice = this.dprice + mprice;
                    }
                }
                if (PAYMODE == 1) {
                    RxToast.normal(PaymentActivity.this, "请填写金额").show();
                } else if (PAYMODE == 2) {
                    RxToast.normal(PaymentActivity.this, "请选择付款方式").show();
                } else if (dprice == 0) {
                    RxToast.normal(PaymentActivity.this, "金额不能为0").show();
                } else {
                    setDialog();
                }
                break;
        }
    }

    public void getOrderSava(String receiptNumber) {
        if (orderSavePresenter.isViewAttached()) {
            HashMap<String, String> map = new HashMap<>();

            if ("全款".equals(mType)){
                map.put("pay_method", "1");
            }else if ("使用定金".equals(mType)){
                map.put("pay_method", "2");
                if ("1".equals(type)) {
                    map.put("member_id", member_id);
                    map.put("deposit_price", edDeposit.getText().toString());
                }
            }
            map.put("pay_info", jsonString);
            map.put("pay_money", String.valueOf(dprice));
            map.put("cashier_name", UserUtils.getUserName(PaymentActivity.this));
            map.put("receipt_number", receiptNumber);
            orderSavePresenter.getOrderSave(map);
        }
    }

    public void getDeposit() {
        if (depositPresenter.isViewAttached()) {
            HashMap<String, String> map = new HashMap<>();
            map.put("member_id", member_id);
            depositPresenter.getDeposit(map);
        }
    }

    @Override
    public void showToast(String msg, String state) {
    }

    @Override
    public void setDeposit(DepositModel data) {
        if (data.getCode() == 1) {
            mdeposit = data.getData().getDeposit();
            tvDeposit.setText(mdeposit+"");
        }else {
            tvDeposit.setText(mdeposit+"");
            RxToast.normal(PaymentActivity.this,data.getMessage()).show();
        }
    }

    @Override
    public void setOrderSava(OrderSaveModel data) {
        if (data.getCode() == 1) {
            RxToast.normal(PaymentActivity.this, data.getMessage()).show();
            order_id = String.valueOf(data.getData().getOrder_id());
            ARouter.getInstance().build("/main/ConfirmContractActivity").withString("order_id", order_id).navigation();
        } else {
            RxToast.normal(PaymentActivity.this, data.getMessage()).show();
        }
    }

    @Override
    public void setUserPay(UserPayModel data) {
        if (data.getCode() == 1) {
            pay_method = data.getData().getPay_method();
            popPayMethodCheckChooseID = new PopPayMethodCheckChooseID(PaymentActivity.this, pay_method);
            popPayMethodCheckChooseID.setTagTxt("请选择")//设置顶部title的内容
                    .setButtomTxt("取消")//设置底部按钮内容
                    .setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);//单选
            //单选
            popPayMethodCheckChooseID.setOnEventLisenter(positionList -> {
                popPayMethodCheckChooseID.dismiss();
                paymentBean = paymentBeansList.get(POSITION);
                paymentBean.setPayment(pay_method.get(positionList.get(0)).getPay_name());
                paymentBean.setType(String.valueOf(pay_method.get(positionList.get(0)).getPay_mode()));
                paymentTypeAdapter.setList(paymentBeansList);
            });
        } else {

        }
    }

    @Override
    public void showLoading() {
        showLoadingDialog();
    }

    @Override
    public void hideLoading() {
        dismissLoadingDialog();
    }

    @Override
    public Context getMyContext() {
        return this;
    }

    public void setDialog() {
        final RxDialogSureCancel rxDialogSureCancel = new RxDialogSureCancel(PaymentActivity.this);
        rxDialogSureCancel.setTitle("提示");
        rxDialogSureCancel.setContent("确定已经收过款了吗？");
        rxDialogSureCancel.getCancelView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rxDialogSureCancel.cancel();
            }
        });
        rxDialogSureCancel.getSureView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rxDialogSureCancel.cancel();
                getOrderSava(receiptNumber);
            }
        });
        rxDialogSureCancel.show();
    }

    //    @Override
//    public void onEditTextAfterTextChanged(Editable editable, int position) {
//        POSITION = position;
//        paymentBean = paymentBeansList.get(POSITION);
//        paymentBean.setPrice(editable.toString());
//    }
    //关闭软键盘
    public void hideIputKeyboard() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                InputMethodManager mInputKeyBoard = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                if (getCurrentFocus() != null) {
                    mInputKeyBoard.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                            InputMethodManager.HIDE_NOT_ALWAYS);
                    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
                }
            }
        });
    }

    @Override
    public void onEditTextAfterTextChanged(Editable editable, int position) {
        paymentBean = paymentBeansList.get(position);
        paymentBean.setPrice(editable.toString());
        paymentTypeAdapter.setNewData(paymentBeansList);

    }

    @Override
    protected void onResume() {
        super.onResume();
        recycleType.addOnItemTouchListener(onTouchListener);
    }

    @Override
    protected void onPause() {
        super.onPause();
        recycleType.removeOnItemTouchListener(onTouchListener);
    }
//
//    @Override
//    public void onPointerCaptureChanged(boolean hasCapture) {
//
//    }
}
